package cn.tedu.egweibo0416.controller;

import cn.tedu.egweibo0416.base.response.JsonResult;
import cn.tedu.egweibo0416.base.response.StatusCode;
import cn.tedu.egweibo0416.mapper.WeiboMapper;
import cn.tedu.egweibo0416.pojo.dto.WeiboAddParam;
import cn.tedu.egweibo0416.pojo.entity.Weibo;
import cn.tedu.egweibo0416.pojo.vo.UserVO;
import cn.tedu.egweibo0416.pojo.vo.WeiboIndexVO;
import cn.tedu.egweibo0416.pojo.vo.WeiboVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Api(tags = "2.微博模块")
@Slf4j
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @PostMapping("insert")
    @ApiOperation("发布微博功能")
    @ApiOperationSupport(order = 10)
    public JsonResult insertWeibo(@RequestBody WeiboAddParam weiboAddParam, @ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboAddParam,weibo);
        weibo.setCreateTime(new Date());
        weibo.setUserId(userVO.getId());
        int num = weiboMapper.insertWeiboInfo(weibo);
        if (num > 0){
            return new JsonResult(StatusCode.OPERATION_SUCCESS);
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }
    @GetMapping("select")
    @ApiOperation("微博首页列表")
    @ApiOperationSupport(order = 20)
    public JsonResult resultSelect(){
        List<WeiboIndexVO> weiboIndex = weiboMapper.resultSelect();
        if (weiboIndex == null){
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
        return JsonResult.ok(weiboIndex);
    }
    @GetMapping("selectById")
    @ApiOperation("查询微博详情")
    @ApiOperationSupport(order = 30)
    public JsonResult selectById(@Range(min = 1,max = 100,message = "id必须在1~100之间")
                                     @RequestParam Long id,@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        WeiboVO weiboVO = weiboMapper.selectById(id);
        if (weiboVO == null){
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
        return JsonResult.ok(weiboVO);
    }





}
